//
//  ComposeViewController.swift
//  Weibo
//
//  Created by 孙明海 on 16/2/27.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import UIKit
import SVProgressHUD


class ComposeViewController: UIViewController {
    /// 照片选择器
    private lazy var pictureVc = PicturePickerController()
    
    /// 表情键盘视图
    private lazy var emoticonView: EmoticonView = EmoticonView {[weak self] (emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }
    // MARK: - 监听方法
    /// 发布微博
    @objc private func sendStatus() {
        print("发布微博")
        let text = textView.emoticonText
        let images = pictureVc.pictures
        
        NetworkTools.sharedNetworkTools.sendStatus(text, images: images) { (result, error) -> (Void) in
            if error != nil {
                print("出错了")
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            self.close()
        }
    }
    
    /// 关闭控制器
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    /// 选择表情键盘
    @objc private func selectEmoticon() {
        
        textView.resignFirstResponder()
        textView.inputView = (textView.inputView == nil) ? emoticonView : nil
        
        textView.becomeFirstResponder()
    }
    /// 选择照片选择器
    @objc private func selectPictureView() {
        textView.resignFirstResponder()
        if pictureVc.view.frame.height > 0 {
            return
        }
        
        pictureVc.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(pictureVc.view.snp_top)
        }
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - 键盘处理
    @objc private func keyboardChange(notification: NSNotification) {
        let rect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as!NSValue).CGRectValue()
        let duration = (notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let curve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        let offset = -self.view.frame.height + rect.origin.y
        
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
    }

    // MARK: - 生命周期方法
    override func loadView() {
        view = UIView()
        
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 让它不会自动调整frame  (如果为true textView 的 contentoff 会自动向下偏移)
        automaticallyAdjustsScrollViewInsets = false
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    // MARK: - 懒加载空间
    private lazy var toolBar = UIToolbar()
    
    private var textView: UITextView = {
       let textView = UITextView()
        
        textView.textColor = UIColor.darkGrayColor()
        textView.font = UIFont.systemFontOfSize(18)
        // 始终允许垂直滚动
        textView.alwaysBounceVertical = true
        // 拖拽时键盘退出
        textView.keyboardDismissMode = .OnDrag
        
        return textView
    }()

}
// MARK: - 设置界面
extension ComposeViewController {
    
    private func setupUI() {
        
        // 设置背景颜色
        view.backgroundColor = UIColor.whiteColor()
        
        // 设置空间
        prepareNavigationBar()
        prepareToobar()
        prepareTextView()
        preparePictureView()
    }
    private func preparePictureView() {
        self.addChildViewController(pictureVc)
        
        view.insertSubview(pictureVc.view, belowSubview: toolBar)
        
        pictureVc.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(0)
        }
    }
    
    private func prepareToobar() {
        view.addSubview(toolBar)
        toolBar.backgroundColor = UIColor(white: 0.7, alpha: 1)
        toolBar.tintColor = UIColor.orangeColor()
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.height.equalTo(44)
        }
        
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPictureView"],
                ["imageName": "compose_mentionbutton_background"],
                ["imageName": "compose_trendbutton_background"],
                ["imageName": "compose_emoticonbutton_background","actionName": "selectEmoticon"],
                ["imageName": "compose_addbutton_background"]
        ]
        
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(item)
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolBar.items = items
    }
    
    /// 设置textView
    private func prepareTextView() {
        
        view.addSubview(textView)
        textView.backgroundColor = UIColor.lightGrayColor()
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(self.view.snp_left)
            make.bottom.equalTo(self.toolBar.snp_top)
            make.right.equalTo(self.view.snp_right)
        }
    }
    
    
    /// 设置导航栏
    private func prepareNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "sendStatus")
        
        // 设置标题视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        navigationItem.titleView = titleView
        
        // 添加子控件
        let titleLabel = UILabel(title: "发微博", fontSize: 15)
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.account?.screen_name ?? "",
            fontSize: 13,
            color: UIColor.lightGrayColor())
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
}
